import {Directive, ElementRef, HostListener, Input} from '@angular/core';
import {Platform} from 'ionic-angular';

/**
 * Generated class for the ForbidEmojiDirective directive.
 *
 * See https://angular.io/api/core/Directive for more info on Angular
 * Directives.
 */
@Directive({
    selector: '[input-correction]' // Attribute selector
})
export class InputCorrectionDirective {

    constructor(public el: ElementRef, private platform: Platform) {
    }

    @Input('input-correction') correctionType: string;

    @HostListener('input', ['$event.target'])
    onInput() {
        this.eventHandle(1);
    }

    @HostListener('focus', ['$event.target'])
    onFocus() {
        this.eventHandle(1);
    }

    @HostListener('blur', ['$event.target'])
    onBlur() {
        this.eventHandle(2);
    }

    eventHandle(params) {
        let $input = this.el.nativeElement.querySelector('input');
        if (this.correctionType === 'integer') {
            let val = $input.value.replace(/[^0-9]/ig, '');
            if ($input.value.length > 1) {
                val = val.replace(/^[0]+/, '')
            }
            $input.value = val;
        }

        if (this.correctionType === 'float') {
            let val = $input.value.replace(/[^\d|.]/ig, '');
            //去掉不合法的首位0
            if (val.length > 1 && val.indexOf('0') === 0 && val.indexOf('.') !== 1){
                let arr = val.split('');
                val = arr.slice(1, arr.length).join();
            }
            //去掉第二个小数点
            if (this.countNum(val, '.') > 1) {
                let arr =  val.split('');
                val = arr.slice(0, arr.length -1).join();
            }
            $input.value = val;
        }
        if (params === 1) {
            $input.focus();
        } else {
            $input.blur();
        }
    }

    /**
     * 计算字符串中各个字符出现的次数
     * @param str
     */
    countNum(str, key) {
        let obj = {};
        str.split('').sort().join('').replace(/(.)(\1+)?/g, (m, k) => {
            obj[k] = m.length
        });
        return obj[key];
    }

}
